/**
 * Created by caojie on 16/3/25.
 */


var mysql = require('mysql');
var $conf = require('../conf/db');
var $sql = require('./regSqlMapping');
var format = require('string-format');


var pool = mysql.createPool($conf.mysql);


var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.status(400);
        res.json({
            code: '-1',
            msg: '操作失败'
        });
    } else if (ret.code == -1) {
        res.status(400);
        res.json(ret);
    } else {
        res.json(ret);

    }
};

module.exports = {

    queryAll: function (req, res, next) {
        pool.getConnection(function (err, connection) {
            connection.query($sql.queryAll, function (err, result) {
                jsonWrite(res, result);
                connection.release();
            });
        });
    },
    register: function(userName, userPwd, res, next){
        pool.getConnection(function (err, connection) {
            if (err) {
                jsonWrite(res, {code: -1, msg: err});
                return;
            }
            var accountField = 'Tel';
            if (userName.indexOf('@')>=0 ) {
                accountField = 'eMail';
            }
            var sqlid='select * from p_user_data ORDER BY ID DESC';
            console.log(sqlid);

            connection.query(sqlid, function (err, result) {
                var userid=0;
                if (result && result.length != 0) {
                    userid=result[0].ID;
                    userid++;
                    //jsonWrite(res, result[0]);
                }
                else {
                    jsonWrite(res, {code: -1, msg: '未查到任何用户'});
                }
                console.log(userid);
                var sql = format('{} {} {} {}', $sql.insert,'(id,'+ accountField+','+ 'pwd)', 'VALUES'+ '('+userid+',\''+userName+'\',',userPwd+')');
                console.log(sql);
                connection.query(sql, function (err, result) {
                    if (result) {
                        result = {
                            code: 200,
                            msg: '注册成功'
                        };
                    }
                    jsonWrite(res, result);
                });
               connection.release();
            });
        })
    }
};
